<template>
  <div class="page-container">
    <carStatistics @statisticsSearch="statisticsGet" ref="statisticsGets" />
    <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" @change="searcherChange" />
    <table-index :table="table" @loadData="loadData">
      <template #carmsg="{ record }">
        <div class="car-msg">
          <div class="car-msg-left">
            <div class="col-lic">
              车牌号：{{ record.licenseNo || '-' }}
              <div v-if="record.modelPhoneUrl" class="col-img" @click="previewFn(record.modelPhoneUrl)">查看车辆图片</div>
            </div>
            <a-popover position="right">
              <div class="truncate">车型：{{ record.modelName || '-' }} </div>
              <template #content>
                {{ record.modelName || '-' }}
              </template>
            </a-popover>
            <div class="col-text">车架号：{{ record.vin || '-' }}</div>
            <div class="col-text" v-if="record.carColor">颜色：{{ record.carColor }}</div>
            <div class="col-text" v-if="record.driveNatureOwner">所属人：{{ record.driveNatureOwner }}</div>
          </div>
        </div>
      </template>
      <!-- 下次保养里程 -->
      <template #estimatedKilometre="{ record }">
        <div class="col-text">{{ isValid(record.estimatedKilometre) ? record.estimatedKilometre : '-' }}</div>
        <carListModel type="mileage" value="estimatedKilometre" :record="record" />
      </template>
      <!-- 保养到期日 -->
      <template #estimatedTime="{ record }">
        <div v-if="record.estimatedTime">
          <div class="col-text">{{ record.estimatedTime || '-' }}</div>
          <carListModel :date="record.estimatedTime" />
        </div>
        <div v-else>-</div>
      </template>
      <!-- 交强险到期日 -->
      <template #compulsoryEndDate="{ record }">
        <div v-if="record.compulsoryEndDate">
          <div class="col-text">{{ record.compulsoryEndDate || '-' }}</div>
          <carListModel :date="record.compulsoryEndDate" />
        </div>
        <div v-else>-</div>
      </template>
      <!-- 商业险到期日 -->
      <template #businessEndDate="{ record }">
        <div v-if="record.businessEndDate">
          <div class="col-text">{{ record.businessEndDate || '-' }}</div>
          <carListModel :date="record.businessEndDate" />
        </div>
        <div v-else>-</div>
      </template>
      <template #etcWorkStatusName="{ record }">
        {{ record.etcWorkStatusName }}
        <!-- 标签 -->
        <div v-if="record.etcSourceName">
          <a-tag :color="getTagColor(record.etcSourceName)">
            {{ record.etcSourceName }}
          </a-tag>
        </div>
      </template>

      <!-- 年检到期日 -->
      <template #planTime="{ record }">
        <div v-if="record.planTime">
          <div class="col-text">{{ record.planTime || '-' }}</div>
          <carListModel type="date" :date="record.planTime" />
        </div>
        <div v-else>-</div>
      </template>

      <template #operateStatusName="{ record }">
        {{ record.operateStatusName }}
        <div :class="[record.orderList?.length > 2 && !record.showTrigger ? 'height-48' : '']">
          <a-link v-for="item in record.orderList" :key="item.refId" class="a-link" @click="() => onALinkClick(item)">
            <span class="order-no">{{ item.typeName }}单号: {{ item.code }}</span>
          </a-link>
        </div>
        <div class="trigger-box" v-if="record.orderList?.length > 2" @click="() => onTrigger(record)">
          <template v-if="record.showTrigger">
            <div class="close">收起</div>
            <icon-up class="icon" />
          </template>
          <template v-else>
            <div class="open">展开</div>
            <icon-down class="icon" />
          </template>
        </div>
      </template>
      <template #orderNo="{ record }">
        <div class="order-no-wrap" v-if="Array.isArray(record.orderList) && record.orderList.length > 0">
          <p class="order-no" v-for="(item, index) in record.orderList.slice(0, 2)" :key="index">{{ item }}</p>
          <p class="order-no more" v-if="record.orderList.length > 2" @mouseenter="moreOver(record)" @mouseleave="moreOut()">...</p>
        </div>
      </template>
      <template #qrcode>
        <a-popover title="">
          <a-button type="primary" @click="carQrcodeModalRef.open()">
            商户挪车二维码
            <icon-question-circle style="margin-left: 5px" />
          </a-button>
          <template #content>
            <p>微信扫描挪车二维码，展示承租人的电话，</p>
            <p>无订单时则展示归属门店联系电话</p>
          </template>
        </a-popover>
      </template>
    </table-index>
  </div>

  <!-- 更换车牌 -->
  <change-license ref="changelicense" @savelicense="saveLicense" />
  <!-- 处置 -->
  <car-dispose ref="cardispose" v-model="disposeVisible" v-model:okLoading="disposeOkLoading" @savedispose="saveDispose" />
  <!-- 导入 -->
  <import-modal ref="imoportRef" action="/carInfo/importExcel" download-import="carList" @ok="loadData" />
  <!-- 购置费导入 -->
  <import-modal
    title="车辆购置费Excel导入"
    ref="imoportAmountRef"
    action="/carAssetFee/importCarAssetFeeExcel"
    :customDownloadList="[
      { key: 'carPurchaseNotStaged', name: '下载不分期导入模版' },
      { key: 'carPurchase', name: '下载分期导入摸板' },
    ]"
    @ok="loadData"
  />
  <!-- 车辆更新导入 -->
  <import-modal ref="imoportCarUpdateRef" action="/carInfo/importUpdateExcel" download-import="carUpdate" @ok="loadData" />
  <!-- 运维导入 -->
  <import-modal ref="assetsImoportRef" download-import="carAssets" @ok="loadData" />

  <a-image-preview-group v-model:visible="previewVisible" v-model:current="previewCurrent" :maskClosable="false" :srcList="previewList" />

  <!-- 添加费用 -->
  <car-add-cost-modal ref="carAddModalRef" @ok="onCarAddModalOk" />
  <!-- 更改车型 -->
  <car-change-model-modal v-model="modelVisible" v-model:ok-loading="okLoading" :details="modelDetails" @ok="onOkModel" />
  <car-delete-modal v-model="deleteVisible" :data="tableRowRecord" @ok="loadData" />
  <!-- 商户挪车二维码 -->
  <car-qrcode-modal ref="carQrcodeModalRef" />
  <!-- 归还 -->
  <return-car model="carManage" ref="return_car" @ok="loadData" />
</template>

<script setup name="CarManageList">
  import { useExport } from '@/hooks/list'
  import changeLicense from '../car-manage/components/car-changelicense.vue'
  import carStatistics from '../car-manage/components/car-statistics.vue'
  import carDispose from '../car-manage/components/car-dispose.vue'
  import carAddCostModal from '../../car/car-manage/components/car-add-cost-modal.vue'
  import carChangeModelModal from '../car-manage/components/car-change-model-modal.vue'
  import carDeleteModal from '../car-manage/components/car-delete-modal.vue'
  import carQrcodeModal from '../car-manage/components/car-qrcode-modal.vue'
  import ReturnCar from '../../operation/car-transfer/compoents/returnCar.vue'
  import carListModel from './components/car-list-model.vue'
  import { onMounted, ref, reactive, computed, nextTick, h, watch } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import {
    getCarList,
    carExportExcel,
    cartoList,
    searchForStaff,
    updateOtherFee,
    checkDisposal,
    updateDisposal,
    updateCarModel,
  } from '@/api/asset/car'
  import useNavigate from '@/hooks/useNavigate'
  import { ruleDetail } from '@/api/system/backlogrule'
  import { useRoute } from 'vue-router'
  import useUserStore from '@/store/modules/user'
  import usePermissionStore from '@/store/modules/permission'
  import dayjs from 'dayjs'
  import { isValid, evalQueryParam } from '@/utils'

  // 根据商户是否开启etc和tbox来增加搜索条件和对应列
  const userStore = useUserStore()
  userStore.setEpDetail()

  const permissionStore = usePermissionStore()
  const { navigateTo } = useNavigate()
  const route = useRoute()

  const imoportRef = ref(null)
  const imoportAmountRef = ref(null)
  const assetsImoportRef = ref(null)
  const carQrcodeModalRef = ref(null)
  const imoportCarUpdateRef = ref(null)
  // 归属门店跳转后回显
  const oldId = ref(null)
  const oldIdList = ref(null)

  import { useSysDict, usePageDict } from '@/hooks/useDict'
  import { Message, Modal } from '@arco-design/web-vue'
  const carManageDict = usePageDict('carManageDict')
  useSysDict(['carInfo_driveNature', 'indicator_plate_type', 'car_index_property'])

  // 归还
  const return_car = ref(null)
  const handleReturn = (record) => {
    return_car.value.show(record)
  }

  // 接口参数（不包含page信息）
  const queryParam = reactive({})
  // 查询条件
  const searchList = computed(() => {
    const searchTempArr = reactive([])
    if (userStore.enterpriseDetail.hrhcEtcEnabled == 1 || userStore.enterpriseDetail.quantumEtcEnabled == 1) {
      // 好人好车etc服务 0:关闭 1:开启
      searchTempArr.push({ label: 'ETC工作状态', prop: 'etcWorkStatus', type: 'a-select', options: carManageDict.etcWorkStatusList })
    }
    // 好人好车Tbox服务 0:关闭 1:开启
    userStore.enterpriseDetail.tboxEnabled == 1 &&
      searchTempArr.push({
        label: '车载BOX设备状态',
        prop: 'tboxEquipmentStatus',
        type: 'a-select',
        options: carManageDict.tboxEquipmentStatusList,
      })

    return [
      { label: '车牌号', prop: 'licenseNoLike', type: 'a-input', span: 1, maxlength: 10 },
      {
        label: '品牌',
        prop: 'brandId',
        type: 'remote-select',
        attrs: {
          type: 'search_car_brand',
          params: {
            id: queryParam.brandId,
          },
        },
        change: (val, option) => {
          if (val) {
            queryParam.brandId = option.id
          }
          queryParam.seriesId = ''
          queryParam.modelId = ''
        },
      },
      {
        label: '车系',
        prop: 'seriesId',
        type: 'remote-select',
        attrs: {
          type: 'car_model_tenant_carList',
          params: {
            brandId: queryParam.brandId,
          },
        },
        change: (val, option) => {
          if (val) {
            queryParam.seriesId = option.id
          }
          queryParam.modelId = ''
        },
      },
      {
        label: '车型',
        prop: 'modelId',
        type: 'remote-select',
        attrs: {
          type: 'car_model_tenantList',
          params: {
            seriesId: queryParam.seriesId,
          },
        },
        change: (val, option) => {
          if (val) {
            queryParam.modelId = option.id
          }
        },
      },
      {
        label: '运营状态',
        prop: 'operateStatusList',
        type: 'a-select',
        multiple: true,
        options: carManageDict.operateStatusList,
      },
      {
        label: '归属门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
          params: {
            oldId: oldId.value,
            idList: oldIdList.value,
          },
        },
      },
      {
        label: '车辆来源',
        prop: 'sourceIdList',
        type: 'a-select',
        multiple: true,
        options: carManageDict.sourceEnumList,
      },
      {
        label: '车辆占用情况',
        prop: 'tagStatusList',
        type: 'a-select',
        options: carManageDict.tagStatusEnums,
        multiple: true,
      },
      {
        label: '年检到期日',
        prop: 'planTime',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.planTimeStart = value[0]
          queryParam.planTimeEnd = value[1]
        },
      },
      {
        label: '交强险到期日',
        prop: 'compulsoryEndDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.compulsoryEndDateStart = value[0]
          queryParam.compulsoryEndDateEnd = value[1]
        },
      },
      {
        label: '商业险到期日',
        prop: 'businessEndDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.businessEndDateStart = value[0]
          queryParam.businessEndDateEnd = value[1]
        },
      },
      {
        label: '距下次保养里程小于等于',
        prop: 'nextMaintenanceMileage',
        type: 'a-input-number',
      },
      {
        label: '保养到期日',
        prop: 'nextMaintenanceDate',
        type: 'i-range-picker',
        change: (value = []) => {
          queryParam.nextMaintenanceDateStart = value[0]
          queryParam.nextMaintenanceDateEnd = value[1]
        },
      },
      {
        label: '车架号',
        prop: 'vin',
        type: 'a-input',
      },
      ...searchTempArr,
      {
        label: 'ETC服务商',
        prop: 'etcSource',
        type: 'a-select',
        options: carManageDict.etcSourceEnums,
      },
    ]
  })

  const carAddModalRef = ref()
  const modelVisible = ref(false)
  const okLoading = ref(false)
  const modelDetails = ref({})

  const onOkModel = (options) => {
    Modal.confirm({
      title: '提示',
      content: h('div', {}, [
        h('p', {}, '车辆修改车型后，所有相关历史数据都会变更，包含车辆、订单、运维、财务、数据汇总等，是否要变更车型？'),
        h('p', { style: 'color: #f50' }, '注：更换车型后，车辆相关数据都需要变更为新车型，操作完成后，请等待5-15分钟后再查看，感谢配合'),
      ]),
      onOk: () => {
        console.log('onOkModel', options)
        updateCarModel({ id: modelDetails.value.id, modelId: options.modelId }).then(() => {
          Message.success('更换车型成功')
          modelVisible.value = false
          loadData()
        })
      },
      onCancel: () => {
        okLoading.value = false
      },
    })
  }

  const deleteVisible = ref(false)
  const tableRowRecord = ref()

  const table = useTable({
    columns: [
      { title: '车辆信息', dataIndex: 'carMsg', width: 320, fixed: 'left', slotName: 'carmsg' },
      { title: '归属门店', dataIndex: 'siteName', width: 120 },
      { title: '归属车场', dataIndex: 'libraryName', width: 150 },
      { title: '车辆来源', dataIndex: 'sourceName', width: 150 },
      {
        title: '车辆购置费总额',
        dataIndex: 'purchaseTotalAmount',
        width: 170,
        unit: '元',
        titleTooltipContent: '车辆购置费或借入费的总额+购置补充费总额',
      },
      { title: '车辆当前里程（公里）', dataIndex: 'totalMileage', width: 180 },
      { title: '下次保养里程（公里）', dataIndex: 'estimatedKilometre', slotName: 'estimatedKilometre', width: 180 },
      { title: '保养到期日', dataIndex: 'estimatedTime', slotName: 'estimatedTime', width: 130 },
      { title: '交强险到期日', dataIndex: 'compulsoryEndDate', slotName: 'compulsoryEndDate', width: 130 },
      { title: '商业险到期日', dataIndex: 'businessEndDate', slotName: 'businessEndDate', width: 130 },
      { title: '年检有效期至', dataIndex: 'planTime', slotName: 'planTime', width: 130 },
      { title: '运营状态', dataIndex: 'operateStatusName', slotName: 'operateStatusName', width: 130 },
      { title: '车辆占用情况', dataIndex: 'tagStatusName', width: 130 },
      { title: '使用性质', dataIndex: 'driverUseNature', width: 130 },
      { title: '注册日期', dataIndex: 'registerDateStr', width: 130 },
      { title: '操作人', dataIndex: 'updateUser', width: 120 },
      { title: '操作时间', dataIndex: 'updateTime', width: 180 },
    ],
    operates: [
      // 租赁中10  空闲可租20   运维中30   已处置40
      {
        label: '详情',
        permission: 'svms:asstes:car:car-model.detail',
        method: (record, column, rowIndex) => {
          console.log(record, column, rowIndex)
          navigateTo(`/car-manage/detail/${record.id}?from=car-manage`, `${record.licenseNo}-车辆详情`)
        },
      },
      {
        label: '编辑',
        permission: 'svms:asstes:car:car-model.edit',
        show: (record) => record.operateStatus != 40,
        method: (record) => {
          navigateTo(`/car-manage/edit/${record.id}`, `${record.licenseNo}-车辆编辑`)
        },
      },
      {
        label: '处置',
        //【租赁中】【已处置】【借调（借入）】，不支持处置操作
        show: (record) => record.operateStatus != 10 && record.operateStatus != 40 && record.source != 2,
        permission: 'svms:asstes:car:car-model.dispose',
        method: (record) => disposeCar({ id: record.id, source: record.source }),
      },
      {
        label: '归还',
        show: (record) => record.source == 2,
        permission: 'svms:asstes:car:car-model.return',
        method: (record) => {
          record.carId = record.id
          handleReturn(record)
        },
      },
      {
        label: '新增保养',
        show: (record) => record.operateStatus != 40,
        permission: 'svms:asstes:car:car-model.maintenance',
        method: (record) => {
          navigateTo(`/car-maintenance/create/${record.id}?page=carManage`, `${record.licenseNo}-新增保养`)
        },
      },
      {
        label: '新增维修',
        show: (record) => record.operateStatus != 40,
        permission: 'svms:asstes:car:car-model.repair',
        method: (record) => {
          navigateTo('/car-repair/create/' + record.id + '?page=carManage', `${record.licenseNo}-新增维修`)
        },
      },
      {
        label: '新增保险',
        show: (record) => record.operateStatus != 40,
        permission: 'svms:asstes:car:car-model.insure',
        method: (record) => {
          navigateTo('/car-insure/create?carId=' + record.id, `${record.licenseNo}-新增保险`)
        },
      },
      {
        label: '新增年检',
        show: (record) => record.operateStatus != 40,
        permission: 'svms:asstes:car:car-model.inspect',
        method: (record) => {
          navigateTo(`/car-inspect/create/${record.id}?carId=${record.id}&page=carManage`, `${record.licenseNo}-新增年检`)
        },
      },
      {
        label: '新增违章',
        permission: 'svms:asstes:car:car-violation.create',
        show: (record) => record.operateStatus != 40,
        method: (record) => {
          navigateTo(`/car-violation/create/${record.id}?page=carManage`, `${record.licenseNo}-新增违章`)
        },
      },
      {
        label: '更换车牌',
        permission: 'svms:asstes:car:car-model.changelicense',
        method: (record) => carlicense(record),
      },
      {
        label: '费用信息',
        permission: 'svms:asstes:car:car-model.cost',
        // show: (record) => record.operateStatus != 40,
        method: (record) => {
          navigateTo(`/car-manage/detail/${record.id}?tab=8&from=car-manage`, `${record.licenseNo}-车辆详情`)
        },
      },
      {
        label: '添加费用',
        permission: 'svms:asstes:car:car-model.addcost',
        show: (record) => record.source !== 2,
        method: (record) => {
          carAddModalRef.value.open(record)
        },
      },
      {
        label: '更换车型',
        permission: 'svms:asstes:car:car-model.changemodel',
        method: (record) => {
          console.log(record, 'record')
          modelVisible.value = true
          modelDetails.value = record
        },
      },
      {
        label: '挪车二维码',
        permission: 'svms:asstes:car:car-model.qrcode',
        method: (record) => {
          carQrcodeModalRef.value.open(record)
        },
      },
      {
        label: '操作记录',
        permission: 'svms:asstes:car:car-model.operaterecords',
        method: (record) => {
          navigateTo(`/car-manage/detail/${record.id}?tab=9&from=car-manage`, `${record.licenseNo}-操作记录`)
        },
      },
      {
        label: '删除',
        show: () => permissionStore.getRoleList.some((item) => item.adminRole === 1),
        // permission: 'svms:asstes:car:car-model.delete',
        method: (record) => {
          deleteVisible.value = true
          tableRowRecord.value = record
        },
      },
    ],
    buttons: [
      {
        type: 'slot',
        label: '商户挪车二维码',
        slotName: 'qrcode',
        permission: 'svms:asstes:car:car-model.qrcode',
        method: () => {
          carQrcodeModalRef.value.open()
        },
      },
      {
        mode: 'import',
        label: '车辆导入',
        permission: 'svms:asstes:car:car-model.import',
        method: () => {
          imoportRef.value.show()
        },
      },
      {
        mode: 'import',
        label: '批量更新车辆',
        permission: 'svms:asstes:car:car-model.carUpdate-import',
        method: () => {
          imoportCarUpdateRef.value.show()
        },
      },
      {
        label: '运维导入',
        permission: 'svms:asstes:car:car-model.assetsImport',
        method: () => {
          assetsImoportRef.value.show()
        },
      },
      {
        mode: 'import',
        label: '购置费导入',
        permission: 'svms:asstes:car:car-model.purchase-cost-import',
        method: () => {
          imoportAmountRef.value.show()
        },
      },
      {
        mode: 'import',
        label: '导出',
        permission: 'svms:asstes:car:car-model.export',
        method: () => handleExport(),
      },
      {
        type: 'primary',
        permission: 'svms:asstes:car:car-model.add',
        mode: 'import',
        icon: 'plus',
        label: '新增',
        method: () => {
          navigateTo('/car-manage/create')
        },
      },
    ],
  })

  // etc和tbox增加对应的列
  watch(
    () => userStore.enterpriseDetail,
    (result) => {
      let { hrhcEtcEnabled, tboxEnabled, quantumEtcEnabled } = result
      let tableTempArr = []
      const etcIndex = table.columns.findIndex((item) => item.title == 'ETC工作状态')
      const tboxIndex = table.columns.findIndex((item) => item.title == '车载BOX设备状态')
      // 好人好车etc服务 0:关闭 1:开启
      if ((hrhcEtcEnabled == 1 || quantumEtcEnabled == 1) && etcIndex == -1) {
        tableTempArr.push({ title: 'ETC工作状态', dataIndex: 'etcWorkStatusName', width: 120, slotName: 'etcWorkStatusName' })
      }
      // 好人好车Tbox服务 0:关闭 1:开启
      tboxEnabled == 1 &&
        tboxIndex == -1 &&
        tableTempArr.push({ title: '车载BOX设备状态', dataIndex: 'tboxEquipmentStatusName', width: 140 })
      let index = table.columns.findIndex((item) => item.dataIndex == 'operateStatusName')
      table.columns.splice(index, 0, ...tableTempArr)
    },
    { deep: true }
  )

  const onTrigger = (e) => {
    e.showTrigger = !e.showTrigger
  }

  const onALinkClick = (item) => {
    if (item.type === 2) {
      navigateTo(`/short-order/detail/${item.refId}?tab=1&carId=${item.carId}`, `${item.code}-短租详情`)
    } else {
      navigateTo(`/long-order/detail/${item.refId}?tab=1&carId=${item.carId}`, `${item.code}-长租详情`)
    }
  }

  // 列表接口调用
  const loadData = (page) => {
    // 重置后，也重置统计样式
    const hasValues = Object.values(queryParam).every((value) => value !== undefined)
    if (!hasValues) {
      resetSn()
    }
    const fn = useFetchTableDataApi(table, queryParam, getCarList)
    fn(page).then((result) => {
      console.log(result, 'result')
      result.data.forEach((item) => {
        if (item.orderList) {
          item.orderList.forEach((e) => {
            e.showTrigger = false
          })
        }
      })
      statisticsGets.value.getStatistic(queryParam)
    })
  }

  const previewVisible = ref(false)
  const previewCurrent = ref(0)
  const previewList = ref([])
  const previewFn = (url) => {
    previewCurrent.value = 0
    previewVisible.value = true
    previewList.value = [url]
  }

  // 筛选发生变化时，清除统计样式
  const searcherChange = () => {
    statisticsGets.value.resetRn()
  }

  // 导出事件
  const handleExport = () => {
    useExport(carExportExcel, queryParam)
  }

  const saveLicense = () => {
    console.log('change')
    loadData()
  }

  const disposeOkLoading = ref(false)
  const disposeVisible = ref(false)

  const saveDispose = (form) => {
    disposeOkLoading.value = true

    checkDisposal({ id: form.id })
      .then((res) => {
        const { prompt } = res.result
        if (prompt) {
          Modal.confirm({
            title: '提示',
            content: prompt,
            onOk: () => {
              updateDisposal({ ...form }).then(() => {
                disposeVisible.value = false
                Message.success('已处置')
                loadData()
              })
            },
          })
        } else {
          updateDisposal({ ...form }).then(() => {
            disposeVisible.value = false
            Message.success('已处置')
            loadData()
          })
        }
      })
      .finally(() => {
        disposeOkLoading.value = false
      })
  }

  // 重置统计选中
  const statisticsGets = ref(null)
  const resetSn = () => {
    statisticsGets.value.resetRn()
    // 清空参数
    queryParam.orNextMaintenanceDateEnd = null
    queryParam.orNextMaintenanceMileage = null
  }

  // 清空筛选
  const resetFn = () => {
    for (const key in queryParam) {
      delete queryParam[key]
    }
  }
  const orderDetail = ref({})
  const getStaticDate = () => {
    ruleDetail().then((res) => {
      orderDetail.value = res.result
    })
  }

  // 点击统计的筛选
  const statisticsGet = (e) => {
    // 重置筛选框
    resetFn()
    // 下滑页面至列表处 没做

    setTimeout(() => {
      if (e == 'totalCount') {
        // 总数 totalCount
        resetFn()
      }
      if (e == 'usableCount') {
        // 可用车辆数 usableCount
        queryParam.operateStatusList = [10, 20, 30]
      }
      if (e == 'selfCarCount') {
        // 自有车辆 selfCarCount
        queryParam.operateStatusList = [10, 20, 30]
        queryParam.sourceIdList = [1]
      }
      if (e == 'loanedCarCount') {
        // 借调车辆 loanedCarCount
        queryParam.operateStatusList = [10, 20, 30]
        queryParam.sourceIdList = [2]
      }
      if (e == 'escrowCarCount') {
        // 托管 escrowCarCount
        queryParam.operateStatusList = [10, 20, 30]
        queryParam.sourceIdList = [4]
      }
      if (e == 'fundingCarCount') {
        // 融资 fundingCarCount
        queryParam.operateStatusList = [10, 20, 30]
        queryParam.sourceIdList = [3]
      }
      if (e == 'recentMaintainCount') {
        // 近期保养 recentMaintainCount
        queryParam.orNextMaintenanceDateEnd = dayjs().add(orderDetail.value.maintenanceBeforeDay, 'day').format('YYYY-MM-DD')
        queryParam.orNextMaintenanceMileage = orderDetail.value.maintenanceBeforeMileage
      }
      if (e == 'recentInspectionCount') {
        // 年检 recentInspectionCount
        queryParam.planTimeEnd = dayjs().add(orderDetail.value.inspectionBeforeDay, 'day').format('YYYY-MM-DD')
      }
      if (e == 'recentRenewInsuranceCount') {
        // 续保 recentRenewInsuranceCount
      }
      if (e == 'recentRenewInsuranceCount') {
        // 交强险
        queryParam.compulsoryEndDateEnd = dayjs().add(orderDetail.value.insureCompulsoryDay, 'day').format('YYYY-MM-DD')
      }
      if (e == 'businessRecentRenewInsuranceCount') {
        // 商业险
        queryParam.businessEndDateEnd = dayjs().add(orderDetail.value.insureBusinessDay, 'day').format('YYYY-MM-DD')
      }
      if (e == 'repairCount') {
        // 维修中 repairCount
        queryParam.tagStatusList = [17]
      }
      if (e == 'rentCount') {
        // 租赁中 rentCount
        queryParam.operateStatusList = [10]
      }
      if (e == 'freeCount') {
        // 空闲可租 freeCount
        queryParam.operateStatusList = [20]
      }
      if (e == 'operationCount') {
        // 运维 operationCount
        queryParam.operateStatusList = [30]
      }
      if (e == 'disposalCount') {
        // 已处置 disposalCount
        queryParam.operateStatusList = [40]
      }
      if (e == 'loanOutCount') {
        // 已借出 loan
        queryParam.operateStatusList = [60]
      }
      loadData()
    }, 200)
  }

  const onCarAddModalOk = (formRef, list, costInfo) => {
    formRef.value.validate((valid) => {
      if (!valid) {
        updateOtherFee({ carId: costInfo.id, operateType: 0, feeList: list }).then((res) => {
          console.log(res)
          carAddModalRef.value.close()
          navigateTo(`/car-manage/detail/${costInfo.id}?tab=8&from=car-manage`, `${costInfo.licenseNo}-车辆详情`)
        })
      }
    })
  }

  // 更换车牌
  const changelicense = ref(null)
  const carlicense = (record) => {
    console.log(record)
    changelicense.value.show(record)
  }

  // 处置
  const cardispose = ref(null)
  const disposeCar = (options) => {
    disposeVisible.value = true
    cardispose.value.show(options)
  }

  // 获取参数
  const pageQueryList = ref({})
  const toPageList = () => {
    cartoList().then((res) => {
      pageQueryList.value = res.result
    })
  }

  // 获取门店
  const storeList = ref([])
  const toStoreList = () => {
    searchForStaff().then((res) => {
      res.result.map((e) => {
        e.value = e.id
        e.label = e.siteName
      })
      storeList.value = res.result
    })
  }

  // 根据标签内容返回不同的颜色值
  const getTagColor = (label) => {
    const tagColors = {
      好人好车: 'orange',
      量子: 'arcoblue',
    }
    return tagColors[label] || 'blue'
  }

  defineExpose({
    saveLicense,
    saveDispose,
  })

  onMounted(() => {
    if (route.query.siteId) {
      queryParam.siteIdList = [route.query.siteId]
      nextTick(() => {
        oldId.value = route.query.siteId
      })
    }
    // 门店列表
    if (route.query.siteIdList) {
      let siteIdList = evalQueryParam(route.query.siteIdList)
      // 门店id转换为数组
      const siteIdList2 = siteIdList.map((item) => String(item))
      queryParam.siteIdList = siteIdList2
      nextTick(() => {
        oldIdList.value = siteIdList2
      })
    }
    if (route.query.operateStatus) {
      queryParam.operateStatusList = [+route.query.operateStatus]
    }
    // 运营状态
    if (route.query.operateStatusList) {
      let operateStatusList = evalQueryParam(route.query.operateStatusList)
      queryParam.operateStatusList = operateStatusList
    }
    // 车辆来源
    if (route.query.sourceIdList) {
      let sourceIdList = evalQueryParam(route.query.sourceIdList)
      queryParam.sourceIdList = sourceIdList
    }
    getStaticDate()
    loadData()
    toPageList()
    toStoreList()
  })
</script>

<style lang="less" scoped>
  .a-link {
    color: rgba(24, 144, 255, 1);
  }
  .height-48 {
    height: 48px;
    overflow: hidden;
  }
  .trigger-box {
    display: flex;
    align-items: center;
    cursor: pointer;
    .open,
    .close {
      font-weight: 400;
      color: rgba(24, 144, 255, 1);
      font-size: 14px;
      margin-right: 4px;
    }
    .icon {
      color: rgba(24, 144, 255, 1);
    }
  }
  .car-msg-left {
    overflow: hidden;
  }
  .car-msg-img {
    width: 100px;
  }
  .col-lic {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    color: #1d2129;
    font-size: 14px;
    font-weight: 600;
  }
  .col-img {
    color: #165dff;
    font-size: 12px;
    text-decoration: underline;
    cursor: pointer;
  }
</style>
